import sqlite3
import os
import tkinter as tk
from tkinter import ttk, messagebox
try:
    from PIL import Image, ImageTk
    import cairosvg
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False
import io

class SVGGallery:
    def __init__(self, parent, db_path="svg_gallery.db"):
        self.parent = parent
        self.db_path = db_path
        self.icon_data = {}  # 存储图标数据的字典
        self.init_database()
        
    def init_database(self):
        """初始化数据库和示例数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # 创建表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS svg_icons (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                svg_content TEXT NOT NULL,
                ai_prompt TEXT NOT NULL,
                category TEXT DEFAULT 'general'
            )
        ''')
        
        # 检查是否已有数据，如果数据少于10条则重新初始化
        cursor.execute('SELECT COUNT(*) FROM svg_icons')
        count = cursor.fetchone()[0]
        
        if count < 10:
            # 清空现有数据
            cursor.execute('DELETE FROM svg_icons')
            # 插入示例数据
            sample_data = [
                # 导航类图标
                ("首页图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
</svg>''', "设计一个简洁的房屋图标，用于表示首页或主页", "导航"),
                
                ("菜单图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</svg>''', "创建一个三条横线的汉堡菜单图标", "导航"),
                
                ("返回图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
</svg>''', "设计一个向左的箭头图标，表示返回或后退", "导航"),
                
                ("前进图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"/>
</svg>''', "创建一个向右的箭头图标，表示前进或下一步", "导航"),
                
                # 用户相关图标
                ("用户图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</svg>''', "创建一个用户头像图标，包含头部和肩膀轮廓", "用户"),
                
                ("用户组图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M16 4c0-1.11.89-2 2-2s2 .89 2 2-.89 2-2 2-2-.89-2-2zm4 18v-6h2.5l-2.54-7.63A1.5 1.5 0 0 0 18.54 7H17c-.8 0-1.54.37-2 1l-3.72 5.58L8.5 11.5C7.67 11.5 7 12.17 7 13s.67 1.5 1.5 1.5l2.78 2.78L8.5 20H7v2h13v-2h-1.5z"/>
</svg>''', "设计一个多人用户组图标，表示团队或群组", "用户"),
                
                ("个人资料图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/>
</svg>''', "创建一个圆形个人资料图标，包含头像轮廓", "用户"),
                
                # 系统功能图标
                ("设置图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/>
</svg>''', "设计一个齿轮形状的设置图标，表示配置和选项", "系统"),
                
                ("搜索图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
</svg>''', "创建一个放大镜图标，用于搜索功能", "工具"),
                
                ("通知图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>
</svg>''', "设计一个铃铛形状的通知图标", "系统"),
                
                ("下载图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
</svg>''', "创建一个向下箭头的下载图标", "工具"),
                
                ("上传图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
</svg>''', "设计一个向上箭头的上传图标", "工具"),
                
                # 商务购物图标
                ("购物车图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M7 18c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12L8.1 13h7.45c.75 0 1.41-.41 1.75-1.03L21.7 4H5.21l-.94-2H1zm16 16c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</svg>''', "创建一个购物车图标，用于电商应用", "商务"),
                
                ("购物袋图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M19 7h-3V6a4 4 0 0 0-8 0v1H5a1 1 0 0 0-1 1v11a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V8a1 1 0 0 0-1-1zM10 6a2 2 0 0 1 4 0v1h-4V6zm8 13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V9h2v1a1 1 0 0 0 2 0V9h4v1a1 1 0 0 0 2 0V9h2v10z"/>
</svg>''', "设计一个购物袋图标，表示购买或商品", "商务"),
                
                ("钱包图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</svg>''', "创建一个钱包图标，表示支付或财务", "商务"),
                
                ("信用卡图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/>
</svg>''', "设计一个信用卡图标，用于支付功能", "商务"),
                
                # 情感收藏图标
                ("心形图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12,21.35l-1.45-1.32C5.4,15.36,2,12.28,2,8.5 C2,5.42,4.42,3,7.5,3c1.74,0,3.41,0.81,4.5,2.09C13.09,3.81,14.76,3,16.5,3 C19.58,3,22,5.42,22,8.5c0,3.78-3.4,6.86-8.55,11.54L12,21.35z"/>
</svg>''', "设计一个心形图标，表示喜欢或收藏", "情感"),
                
                ("收藏图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
</svg>''', "创建一个书签形状的收藏图标", "情感"),
                
                ("星星图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
</svg>''', "设计一个五角星图标，表示评分或收藏", "评价"),
                
                ("点赞图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/>
</svg>''', "创建一个竖起大拇指的点赞图标", "情感"),
                
                # 通讯图标
                ("邮件图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>
</svg>''', "设计一个信封形状的邮件图标", "通讯"),
                
                ("电话图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/>
</svg>''', "创建一个电话听筒图标，用于联系功能", "通讯"),
                
                ("消息图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
</svg>''', "设计一个对话气泡消息图标", "通讯"),
                
                ("视频通话图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/>
</svg>''', "创建一个摄像头图标，表示视频通话", "通讯"),
                
                # 应用功能图标
                ("应用图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z"/>
</svg>''', "设计一个九宫格应用图标，表示应用程序", "应用"),
                
                ("文件图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
</svg>''', "创建一个文档文件图标", "工具"),
                
                ("相机图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 15c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3zm0-8c2.76 0 5 2.24 5 5s-2.24 5-5 5-5-2.24-5-5 2.24-5 5-5zm0-1L9 4H7l-1 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-2l-1-2h-2L12 6z"/>
</svg>''', "设计一个相机图标，用于拍照功能", "媒体"),
                
                ("图片图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
</svg>''', "创建一个图片图标，表示图像或相册", "媒体"),
                
                ("音乐图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
</svg>''', "设计一个音符图标，表示音乐或音频", "媒体"),
                
                # 时间日期图标
                ("时钟图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
    <path fill="currentColor" d="M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
</svg>''', "创建一个圆形时钟图标，显示时间概念", "时间"),
                
                ("日历图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
</svg>''', "设计一个日历图标，表示日期或日程", "时间"),
                
                # 其他常用图标
                ("锁定图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/>
</svg>''', "创建一个锁定图标，表示安全或隐私", "安全"),
                
                ("分享图标", '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path fill="currentColor" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
</svg>''', "设计一个分享图标，表示分享或传播", "工具")
            ]
            
            cursor.executemany(
                'INSERT INTO svg_icons (name, svg_content, ai_prompt, category) VALUES (?, ?, ?, ?)',
                sample_data
            )
        
        conn.commit()
        conn.close()
    
    def open_gallery(self):
        """打开图库窗口"""
        self.gallery_window = tk.Toplevel(self.parent)
        self.gallery_window.title("SVG图标图库")
        self.gallery_window.geometry("800x600")
        self.gallery_window.transient(self.parent)
        
        # 居中显示
        self.gallery_window.geometry("+%d+%d" % (
            self.parent.winfo_rootx() + 100, 
            self.parent.winfo_rooty() + 50
        ))
        
        self.setup_gallery_ui()
        self.load_gallery_data()
    
    def setup_gallery_ui(self):
        """设置图库界面"""
        # 主框架
        main_frame = ttk.Frame(self.gallery_window, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 搜索框架
        search_frame = ttk.Frame(main_frame)
        search_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(search_frame, text="搜索:").pack(side=tk.LEFT)
        self.search_var = tk.StringVar()
        self.search_var.trace_add('write', self.on_search_change)
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=30)
        search_entry.pack(side=tk.LEFT, padx=(5, 10))
        
        ttk.Button(search_frame, text="清空", command=self.clear_search).pack(side=tk.LEFT)
        
        # 图标列表框架
        list_frame = ttk.Frame(main_frame)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建Treeview
        columns = ('name', 'category', 'prompt')
        self.tree = ttk.Treeview(list_frame, columns=columns, show='tree headings', height=15)
        
        # 设置列标题和宽度
        self.tree.heading('#0', text='图标')
        self.tree.heading('name', text='名称')
        self.tree.heading('category', text='分类')
        self.tree.heading('prompt', text='AI提示词')
        
        self.tree.column('#0', width=80, minwidth=80)
        self.tree.column('name', width=120, minwidth=100)
        self.tree.column('category', width=80, minwidth=80)
        self.tree.column('prompt', width=400, minwidth=200)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0))
        
        ttk.Button(button_frame, text="复制SVG", command=self.use_selected_icon).pack(side=tk.LEFT)
        ttk.Button(button_frame, text="复制提示词", command=self.copy_prompt).pack(side=tk.LEFT, padx=(10, 0))
        ttk.Button(button_frame, text="保存SVG", command=self.save_selected_svg).pack(side=tk.LEFT, padx=(10, 0))
        ttk.Button(button_frame, text="关闭", command=self.gallery_window.destroy).pack(side=tk.RIGHT)
    
    def load_gallery_data(self, search_term=""):
        """加载图库数据"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        self.icon_data.clear()  # 清空图标数据字典
        
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        if search_term:
            cursor.execute(
                'SELECT id, name, svg_content, ai_prompt, category FROM svg_icons WHERE name LIKE ? OR ai_prompt LIKE ? OR category LIKE ?',
                (f'%{search_term}%', f'%{search_term}%', f'%{search_term}%')
            )
        else:
            cursor.execute('SELECT id, name, svg_content, ai_prompt, category FROM svg_icons')
        
        icons = cursor.fetchall()
        conn.close()
        
        for icon in icons:
            icon_id, name, svg_content, ai_prompt, category = icon
            
            # 尝试渲染SVG为小图标
            if PIL_AVAILABLE:
                try:
                    png_data = cairosvg.svg2png(bytestring=svg_content.encode('utf-8'), output_width=32, output_height=32)
                    image = Image.open(io.BytesIO(png_data))
                    photo = ImageTk.PhotoImage(image)
                    
                    # 插入到树形视图
                    item = self.tree.insert('', 'end', text='', image=photo, values=(name, category, ai_prompt))
                    # 保存图片引用和数据到字典
                    self.icon_data[item] = (icon_id, svg_content, photo)
                    
                except Exception as e:
                    # 如果渲染失败，使用文本
                    item = self.tree.insert('', 'end', text='[图标]', values=(name, category, ai_prompt))
                    self.icon_data[item] = (icon_id, svg_content, None)
            else:
                # 如果PIL不可用，直接使用文本显示
                item = self.tree.insert('', 'end', text='[图标]', values=(name, category, ai_prompt))
                self.icon_data[item] = (icon_id, svg_content, None)
    
    def on_search_change(self, *args):
        """搜索框内容变化时的回调"""
        search_term = self.search_var.get().strip()
        self.load_gallery_data(search_term)
    
    def clear_search(self):
        """清空搜索"""
        self.search_var.set("")
    
    def use_selected_icon(self):
        """使用选中的图标"""
        selection = self.tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个图标")
            return
        
        item = selection[0]
        if item in self.icon_data:
            icon_id, svg_content, photo = self.icon_data[item]
            # 这里可以将SVG内容传递给主应用
            messagebox.showinfo("成功", "图标已复制到剪贴板")
            self.gallery_window.clipboard_clear()
            self.gallery_window.clipboard_append(svg_content)
    
    def copy_prompt(self):
        """复制选中图标的提示词"""
        selection = self.tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个图标")
            return
        
        item = selection[0]
        values = self.tree.item(item, 'values')
        if values and len(values) >= 3:
            prompt = values[2]  # AI提示词在第3列
            self.gallery_window.clipboard_clear()
            self.gallery_window.clipboard_append(prompt)
            messagebox.showinfo("成功", "提示词已复制到剪贴板")
    
    def save_selected_svg(self):
        """保存选中的SVG文件"""
        selection = self.tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个图标")
            return
        
        item = selection[0]
        if item in self.icon_data:
            icon_id, svg_content, photo = self.icon_data[item]
            name = self.tree.item(item)['values'][0]  # 获取图标名称
            
            # 打开文件保存对话框
            from tkinter import filedialog
            filename = filedialog.asksaveasfilename(
                title="保存SVG文件",
                defaultextension=".svg",
                filetypes=[("SVG files", "*.svg"), ("All files", "*.*")],
                initialfile=f"{name}.svg"
            )
            
            if filename:
                try:
                    with open(filename, 'w', encoding='utf-8') as f:
                        f.write(svg_content)
                    messagebox.showinfo("成功", f"SVG文件已保存到: {filename}")
                except Exception as e:
                    messagebox.showerror("错误", f"保存文件失败: {str(e)}")